package main

import (
	"fmt"
	"sync"
	"time"
)

var bStop = false

func makeStop(work_time int) {
	time.Sleep(time.Duration(work_time) * time.Second)
	bStop = true
}

func producer(threadId int, wg *sync.WaitGroup, ch chan<- int) {
	count := 0
	for !bStop {
		time.Sleep(1 * time.Second)
		count++
		fmt.Println()
		fmt.Println("producer:", threadId, "-->", count)
		ch <- count
	}
	wg.Done()
}
func consumer(threadId int, wg *sync.WaitGroup, ch <-chan int) {
	for i := range ch {
		time.Sleep(2 * time.Second)
		fmt.Println()
		fmt.Println("consumer:", threadId, "-->", i)
	}
	wg.Done()
}
func main() {
	// 生产者快，消费者慢
	ch := make(chan int, 5)
	wgp := new(sync.WaitGroup)
	wgc := new(sync.WaitGroup)

	for i := 0; i < 3; i++ {
		wgp.Add(1)
		go producer(i, wgp, ch)
	}

	for j := 0; j < 3; j++ {
		wgc.Add(1)
		go consumer(j, wgc, ch)
	}

	go makeStop(10)

	wgp.Wait()
	close(ch)
	wgc.Wait()
}
